import { addNewAddress, getAddressList, updateAddress, updateAvatar, updateGender } from "@/api/user";
import { useUserStore } from "@/store";
import { View, Text, Picker, Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useEffect, useState } from "react";
import { AtAvatar, AtButton, AtInput, AtList, AtListItem, AtMessage, AtModal, AtModalAction, AtModalContent, AtModalHeader } from "taro-ui";

const ShowUserInfo: React.FC = () => {
  const userStore = useUserStore();

  useEffect(() => {
    if (userStore.addressList.length > 0) {
      const initialAddress = userStore.addressList.find(item => item.current);
      if (initialAddress) {
        setSelectorChecked(initialAddress.address);
      }
      setPickerData(userStore.addressList.map(item => ({ id: item.id, address: item.address })));
    }

    setGenderSelectorChecked(userStore.gender ? "男" : "女");
    setGenderData([{ id: 1, gender: "男" }, { id: 0, gender: "女" }])
  }, [userStore.addressList, userStore.gender]);

  const [pickerData, setPickerData] = useState<{ id: number; address: string }[]>([]);
  const [selectorChecked, setSelectorChecked] = useState<string>('');

  const [isOpened, setIsOpened] = useState<boolean>(false);
  const [newAddress, setNewAddress] = useState<string>("");

  const onChange = async (e: any) => {
    const { value } = e.detail;
    // console.log(pickerData.find(item => item.address === selectorChecked)?.id);
    // console.log(pickerData[value].id);
    const data = await updateAddress(pickerData.find(item => item.address === selectorChecked)?.id!, pickerData[value].id);
    if (data.code === 200) {
      Taro.atMessage({
        type: "success",
        message: "修改成功",
      })
      const addressList = await getAddressList();

      userStore.setAddressList(addressList.data);
    }
    setSelectorChecked(pickerData[value].address);
  }

  function handleClose(): void {
    setIsOpened(false);
  }

  const handleConfirm = async () => {
    setIsOpened(false);
    const data = await addNewAddress(newAddress);
    if (data.code === 200) {
      Taro.atMessage({
        type: "success",
        message: "新增成功"
      })
      userStore.setAddressList((await getAddressList()).data);
    }
    setNewAddress("");
  }

  const changeNewAddress = (value: string) => {
    setNewAddress(value);
  }

  const changeAvatar = async () => {
    Taro.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        Taro.uploadFile({
          url: "http://127.0.0.1:8080/user/upload",
          filePath: tempFilePaths[0],
          name: "avatar",
          async success(resp) {
            userStore.setAvatar(resp.data);
            const data = await updateAvatar(resp.data);
            if (data.code === 200) {
              Taro.atMessage({
                type: "success",
                message: "修改成功"
              })
            }
          }
        })
      }
    })
  }

  const [genderData, setGenderData] = useState<{ id: number; gender: string }[]>([]);
  const [genderSelectorChecked, setGenderSelectorChecked] = useState<string>('');

  const onChangeGender = async (e: any) => {
    const { value } = e.detail;
    // console.log(genderData[value].gender);
    const data = await updateGender(Boolean(genderData[value].id))
    if (data.code === 200) {
      userStore.setGender(data.data);
      Taro.atMessage({
        type: "success",
        message: "修改成功"
      })
    }
  }

  return (
    <>
      <AtMessage />

      <View className='flex justify-between p-3 items-center'>
        <Text>用户头像</Text>
        <View onClick={changeAvatar}>
          <AtAvatar circle image={userStore.avatar} />
        </View>
      </View>
      <AtList>
        <AtListItem title='用户名' extraText={userStore.username} />
        <Picker mode='selector' range={genderData.map(item => item.gender)} onChange={onChangeGender}>
          <AtList>
            <AtListItem
              title='性别'
              extraText={genderSelectorChecked}
            />
          </AtList>
        </Picker>
      </AtList>

      <Picker mode='selector' range={pickerData.map(item => item.address)} onChange={onChange}>
        <AtList>
          <AtListItem
            title='联系地址'
            extraText={selectorChecked}
          />
        </AtList>
      </Picker>

      <AtButton type='primary' className='mt-3' onClick={() => setIsOpened(true)}>新增联系地址</AtButton>

      <AtModal
        isOpened={isOpened}
        onClose={handleClose}
        className='w-full'
      >
        <AtModalHeader>新增联系地址</AtModalHeader>
        <AtModalContent>
          <AtInput
            name='value'
            type='text'
            placeholder='请输入新增地址...'
            value={newAddress}
            onChange={changeNewAddress}
          />
        </AtModalContent>
        <AtModalAction>
          <Button onClick={handleConfirm}>确定</Button>
        </AtModalAction>
      </AtModal>
    </>
  )
}

export default ShowUserInfo;
